var Game=new function()
{
	var boards=[];
	this.canvas=document.getElementById("game");
	this.ctx=this.canvas.getContext && this.canvas.getContext('2d');
	if(!this.ctx)
	{
		return alert("pelase upgrade your brower");	
	}	
	this.width=this.canvas.width;
	this.height=this.canvas.height;
	
	this.setupMoubile=function()
	{
		hastouch=!!('ontouchstart' in window);
		this.container=document.getElementById("container");
		if(hastouch)
		{
			w=window.innerWidth;
			h=window.innerHeight;
			
			
			pad=Math.floor(Math.abs(h*9/16-w)/2);
			this.container.style.paddingLeft=pad+"px";
			this.container.style.paddingRight=pad+"px";
			
			this.canvas.style.width=w-pad*2+"px";
			this.canvas.style.height=h+"px";
		}
		else
		{
			this.container.style.padding=50+"px";
			this.container.style.textAlign="center";
		}
	}
	
	this.loop=function()
	{
		var dt=30/1000;
		for(var i=0,len=boards.length;i<len;i++)
		{
			if(boards[i])//遍历画出每个层
			{
				boards[i].step(dt); //层的没帧变化
				boards[i].draw(Game.ctx);
			}	
		}
		if(Game.boomTest())
		{
			var endmap=sourcemap['end'];
			Source.draw(Game.ctx,endmap, Math.floor((Game.width-endmap.w)/2),Math.floor((Game.height-endmap.h)/2));
			return;	
		} 
		
		if(Piepline.x+(Piepline.max-1)*Piepline.dx+Piepline.max*Piepline.w < Bird.tx)
		{
			Game.ctx.font="30px sans-serif";
			Game.ctx.strokeText("You Win!",150,220);
			return;
		}
		setTimeout(Game.loop,30);
	};
	
	this.boomTest=function()
	{
		var bx1=Bird.tx; var by1=Bird.ty;
		var bx2=Bird.tx+36; var by2=Bird.ty+24;
		
		if(by2>=this.height-Background.floormap.h)return 1;
		
		for(var i=Piepline.nl; i<=Piepline.nr && Piepline.nr>=1; i++)
		{
			var xl=(i-1)*(Piepline.dx+Piepline.w)+Piepline.x;
			var xr=xl+Piepline.w;
			if(bx1<xr && bx2>xl)
				if(by1<Piepline.top[i] || by2>Piepline.top[i]+Piepline.dh)
					return 1;
			
			return 0;	
		}	
	}
	
	
	
	//设置输入处理
	this.touch=0;
	this.setupInput=function(){
		window.addEventListener('touchstart',function(e){Game.touch=1;e.preventDefault();},false);
		window.addEventListener('keydown',function(e){if(e.which == 38) { Game.touch=1;e.preventDefault();} },false);
	};
	
	//游戏循环
	
	
	//操作层
	this.setboards=function(board,num){boards[num]=board;};
}

var Source = new function()
{
	this.load=function(callback) //图片加载完回调startGame();
	{
		this.image=new Image();
		this.image.onload=callback;
		this.image.src='image/bird.png';	
	};
	
	this.draw=function(ctx,map,x,y,full)
	{
		ctx.drawImage(this.image,map.sx,map.sy,map.w,map.h,x,y,map.w,map.h);
	};
	
}